﻿using AutoMapper;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Infratrveture;
using B.S.Filtration.Read.Api.Application.Command.DOM;
using B.S.Filtration.Read.Api.Dto;
using MediatR;
using SqlSugar;
using System.Data;

namespace B.S.Filtration.Read.Api.Application.CommandHander.DOM
{
    public class GetDOMIdHander : IRequestHandler<GetDOMIdCommand, APIResult<DOMDTO>>
    {
        private readonly IMapper mapper;
        private readonly DapperContext db;

        public GetDOMIdHander(IMapper mapper, DapperContext db)
        {
            this.mapper = mapper;
            this.db = db;
        }
        /// <summary>
        /// id查询DOM信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<DOMDTO>> Handle(GetDOMIdCommand request, CancellationToken cancellationToken)
        {
            APIResult<DOMDTO> result = new APIResult<DOMDTO>();

            var query = @"SELECT * FROM DOM WHERE DOMId = @DOMId";
            var parameters = new { DOMId = request.DOMId };

            try
            {
                // 注意这里使用 QueryFirstOrDefaultAsync<DOMDTO>
                var item = await db.QueryFirstOrDefaultAsync<DOMDTO>(query, parameters);

                if (item != null)
                {
                    result.data = item;
                    result.code = APIResultCode.success;
                    result.msg = "查询成功";
                }
                else
                {
                    result.code = APIResultCode.failed;
                    result.msg = "未找到匹配记录";
                }
            }
            catch (Exception ex)
            {
                result.code = APIResultCode.failed;
                result.msg = "查询失败: " + ex.Message;
                Console.WriteLine($"Error in GetDOMIdHander: {ex.Message}");
            }

            return result;
        }
    }
}